const { readUserData, writeUserData } = require("./request");

const getUserById = (id) => {
  return new Promise(async (resolve, reject) => {
    try {
      const users = await readUserData();
      resolve(users.find((user) => user.id === parseInt(id, 10)));
    } catch (error) {
      reject(error);
    }
  });
};
const hasUser = ({ username, password }) => {
  return new Promise(async (resolve, reject) => {
    try {
      const users = await readUserData();
      const user = users.find(
        (user) => user.name === username && user.password === password
      );
      resolve(user);
    } catch (error) {
      reject(error);
    }
  });
};
const addUser = async ({ username, password, phone }) => {
  return new Promise(async (resolve, reject) => {
    try {
      const users = await readUserData();
      const user = users.find((user) => user.name === username);
      if (user) {
        resolve("User already exists");
      } else {
        users.push({ name: username, password, phone, id: users.length + 1 });
        writeUserData(users).then(() => {
          resolve(true);
        });
      }
    } catch (error) {
      reject(error);
    }
  });
};
module.exports = {
  getUserById,
  hasUser,
  addUser,
};
